import React, { useState, useEffect } from 'react';
import { View, Text, TextInput, TouchableOpacity, Image, StyleSheet, Alert } from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
import ChatImage from '../assets/chat.jpg';
import ImageGallery from "./BottomNav";

const LoginScreen = ({ navigation }) => {

    React.useLayoutEffect(() => {
        navigation.setOptions({
            headerShown: false,
        });
    }, [navigation]);

    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');

    useEffect(() => {
        // 检查本地存储是否有email和password
        checkLocalCredentials();
    }, []);

    const checkLocalCredentials = async () => {
        try {
            const storedEmail = await AsyncStorage.getItem('email');
            const storedPassword = await AsyncStorage.getItem('password');

            if (storedEmail && storedPassword) {
                // 如果本地有数据，自动填充并登录
                setEmail(storedEmail);
                setPassword(storedPassword);
                handleLogin();
            }
        } catch (error) {
            console.error('Error reading local credentials:', error);
        }
    };

    const handleLogin = async () => {
        // 向后台发送账号密码
        // 这里暂时用简单的字符串比较，实际上应该向后台验证
        if (email === password) {
            // 验证成功则存储在本地
            try {
                await AsyncStorage.setItem('email', email);
                await AsyncStorage.setItem('password', password);
            } catch (error) {
                console.error('Error storing local credentials:', error);
            }

            // 然后进入页面
            navigation.navigate('SettingScreen');
        } else {
            // 验证失败则弹出弹窗
            Alert.alert('Error', '邮箱或密码错误');
        }
    };

    return (
        <View style={styles.container}>
            <Image source={ChatImage} style={styles.image} />
            <Text style={styles.title}>Chat </Text>
            <TextInput
                style={styles.input}
                placeholder="Email"
                value={email}
                onChangeText={(text) => setEmail(text)}
                autoCapitalize="none"
            />
            <TextInput
                style={styles.input}
                placeholder="Password"
                value={password}
                onChangeText={setPassword}
                secureTextEntry
            />
            <TouchableOpacity style={styles.button} onPress={handleLogin}>
                <Text style={styles.buttonText}>Login </Text>
            </TouchableOpacity>
            <ImageGallery navigation={navigation} />
        </View>
    );
};

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: "flex-start",
        alignItems: 'center',
        marginTop: 50,
        padding: 16,
    },
    image: {
        width: 100,
        height: 100,
        resizeMode: 'cover',
        marginBottom: 16,
        borderRadius: 15,
    },
    title: {
        fontSize: 24,
        fontWeight: 'bold',
        marginBottom: 16,
    },
    input: {
        height: 40,
        width: '100%',
        borderColor: 'gray',
        borderWidth: 0,
        marginBottom: 12,
        paddingLeft: 8,
        borderRadius: 8,
        backgroundColor: '#fff'
    },
    button: {
        backgroundColor: '#0092fe',
        padding: 12,
        borderRadius: 8,
        width: '100%',
        alignItems: 'center',
    },
    buttonText: {
        color: 'white',
        fontWeight: 'bold',
    },

});

export default LoginScreen;
